package org.aeon.newsmanagersystem.service.impl;

import org.aeon.newsmanagersystem.dao.CommentsMapper;
import org.aeon.newsmanagersystem.pojo.Comments;
import org.aeon.newsmanagersystem.pojo.News;
import org.aeon.newsmanagersystem.pojo.other.PageInfo;
import org.aeon.newsmanagersystem.service.CommentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: MissingAeon
 * @date: 2024/3/27 17:29
 * @description:
 */
@Service
public class CommentsServiceImpl implements CommentsService {
    // ip地址正则
    private static final String regex = "(^((2[0-4]\\d.)|(25[0-5].)|(1\\d{2}.)|(\\d{1,2}.))((2[0-5]{2}.)|(1\\d{2}.)|(\\d{1,2}.){2})((1\\d{2})|(2[0-5]{2})|(\\d{1,2})))";
    private final CommentsMapper commentsMapper;

    @Autowired
    public CommentsServiceImpl(CommentsMapper commentsMapper) {
        this.commentsMapper = commentsMapper;
    }


    @Override
    public PageInfo<Comments, News> newsComments(PageInfo<Comments, News> page) {
        final Integer nid = page.getCondition().getNid();
        // 查询评论
        final List<Comments> comments = commentsMapper.getByNid(nid, page.getStart(), page.getLimit());

        page.setList(comments);
        // 设置总条数
        final int total = commentsMapper.byNidCount(nid);
        page.setTotal(total);

        return page;
    }

    @Override
    public boolean delete(Integer cid) {
        return commentsMapper.deleteByPrimaryKey(cid) == 1;
    }

    @Override
    public boolean add(Comments comments) {

        // return comments.getCip().matches(regex);
        if (!comments.getCip().matches(regex)) {
            comments.setCip("未知");
        }
        return commentsMapper.insert(comments) == 1;
    }
}
